<template>
  <el-dialog
    title="用户注册"
    center
    :visible.sync="dialogVisible"
    width="600px"
    @close="handleClose"
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      :inline="false"
      size="normal"
      label-position="left"
    >
      <el-form-item label="头像" prop="avatar">
        <!--
          action：上传的地址
          show-file-list：是否显示列表
          before-upload: 上传之前（限定格式）
          on-success：上传之后的（预览和给 form.avatar 赋值）
          -->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :data="uploadObj"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="16">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" style="margin-left:15px;">
          <img
            :src="smsCaptchaUrl"
            @click="changeSmsCaptchaUrl"
            alt=""
            style="width:140px;height:40px;"
          />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="验证码" prop="rcode">
            <el-input v-model="form.rcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" style="margin-left:10px;width:140px;">
          <el-button @click="getVcode">获取用户验证码</el-button>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'Register',
  data () {
    return {
      smsCaptchaUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms', // 图形码的地址
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', // 上传头像的地址
      uploadObj: {}, // 上传时候的额外参数对象
      imageUrl: '', // 头像预览
      dialogVisible: false, // 控制对话框的显示与隐藏
      form: {
        // form表单的模型
        username: '',
        phone: '',
        email: '',
        avatar: '', // 头像上传之后的地址
        password: '',
        code: '', // 图形码
        rcode: '' // 验证码
      },
      rules: {
        avatar: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule 规则，基本用不到
              // value 就是你输入的值
              // callback 回到，失败： callback(new Error('错误信息')) 成功：callback，注意：无论成功失败都要调用
              if (!value) {
                callback(new Error('邮箱不能为空'))
                return
              }
              // eslint-disable-next-line
              const reg = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/
              if (!reg.test(value)) {
                callback(new Error('邮箱不合法'))
                return
              }

              // 不要忘记我
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          // { required: true, message: '手机号不能为空', trigger: 'blur' }
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule 规则，基本用不到
              // value 就是你输入的值
              // callback 回到，失败： callback(new Error('错误信息')) 成功：callback，注意：无论成功失败都要调用
              if (!value) {
                callback(new Error('手机号不能为空'))
                return
              }

              const reg = /^1[3-9][0-9]{9}$/
              if (!reg.test(value)) {
                callback(new Error('手机号不合法'))
                return
              }

              // 不要忘记我
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度必须在6-16位之间',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '验证码的长度必须是4位',
            trigger: 'blur'
          }
        ],
        rcode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '验证码的长度必须是4位',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 更改注册时候的图形码
    changeSmsCaptchaUrl () {
      this.smsCaptchaUrl =
        process.env.VUE_APP_BASEURL + '/captcha?type=sendsms&t=' + Date.now()
    },
    // 头像上传相关
    handleAvatarSuccess (res, file) {
      if (res.code === 200) {
        // 预览
        this.imageUrl = URL.createObjectURL(file.raw)

        // 把服务器返回的图像地址赋值给 form.avatar
        this.form.avatar = res.data.file_path
      } else {
        this.$message({
          type: 'error',
          message: res.message,
          duration: 1000
        })
      }
    },
    // 上传之前（限定文件格式）
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG|PNG|GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 给上传头型添加额外参数（这个是后台要求的）, image 属性是接口中规定的
      this.uploadObj.image = file
      // console.log(this.uploadObj.image)

      return isImage && isLt2M
    },
    // 获取验证码
    async getVcode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })

      if (num === 2) {
        const res = await this.$axios.post('/sendsms', {
          phone: this.form.phone,
          code: this.form.code
        })

        if (res.code === 200) {
          this.form.rcode = res.data.captcha
        } else {
          this.$message({
            type: 'error',
            message: res.message,
            duration: 1000
          })

          // 刷新图形码
          this.changeSmsCaptchaUrl()
        }
      }
    },
    submit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const res = await this.$axios.post('/register', this.form)
        if (res.code === 200) {
          // 提示
          this.$message({
            type: 'success',
            message: '注册成功~',
            duration: 1000
          })
          // 关闭弹窗
          this.dialogVisible = false
        } else {
          // 提示
          this.$message({
            type: 'error',
            message: res.message,
            duration: 1000
          })

          // 刷新验证码
          this.changeSmsCaptchaUrl()
        }
      })
    },
    handleClose () {
      this.$refs.form.resetFields()
      //  头像预览要单独清空
      this.imageUrl = ''
      this.changeSmsCaptchaUrl()
    }
  }
}
</script>

<style>
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
